package org.jks.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.jks.constant.Constants;
import org.jks.constant.SysError;
import org.jks.model.Privilege;
import org.jks.model.Role;
import org.jks.model.RolePrivilege;
import org.jks.model.User;

public class PrivilegeUtil {
	public static int hasPrivlege( HttpSession session, String action) {
		User user = (User) session.getAttribute(Constants.SESSION_ACCOUNT);
		if(user == null){
			return SysError.ERR_NOT_LOGIN;
		}
		if(user.getName().equals("admin")){
			return SysError.SUCCESS;
		}
		@SuppressWarnings("unchecked")
		Map<String, Boolean> privileges = (Map<String, Boolean>) session.getAttribute(Constants.SESSION_PRIVILEGES);
		if(privileges == null || action == null){
			return SysError.ERR_NO_PRIVILEGE;
		}
		if(privileges.containsKey(action)){
			return (boolean) privileges.get(action) ? SysError.SUCCESS : SysError.ERR_NO_PRIVILEGE;
		}
		return SysError.ERR_NO_CHECK;
	}

	public static boolean exist(Privilege privilege, long[] privs) {
		if (privilege == null || privs == null || privs.length == 0) {
			return false;
		}
		for (long id : privs) {
			if (privilege.getId() == id) {
				return true;
			}
		}
		return false;
	}

	public static Map<String, Boolean> mergePrivilege(User user) {
		Map<String, Boolean> privileges = new HashMap<String, Boolean>();
		if (user != null && user.getRoles() != null
				&& user.getRoles().size() > 0) {
			for (Role role : user.getRoles()) {
				if (role.getPrivileges() != null
						&& role.getPrivileges().size() > 0) {
					for (RolePrivilege privilege : role.getPrivileges()) {
						if (!privileges.containsKey(privilege.getPrivilege()
								.getAction())) {
							privileges.put(
									privilege.getPrivilege().getAction(),
									privilege.isSelected());
						}
						else if(privilege.isSelected()){
							privileges.put(
									privilege.getPrivilege().getAction(),
									privilege.isSelected());
						}
					}
				}

			}
		}
		return privileges;
	}
}
